package com.yjht.secrity.service;

import com.yjht.secrity.SecurityUtils;
import com.yjht.secrity.auth.AuthUser;
import com.yjht.system.model.Resource;
import com.yjht.system.service.IResourceService;
import net.dreamlu.tool.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

/**
 * 权限判断
 *
 * url: https://stackoverflow.com/questions/41434231/use-spring-security-in-thymeleaf-escaped-expressions-in-javascript
 *
 * @author lengleng
 */
@Service("sec")
public class SecService {

	@Autowired
	private IResourceService resourceService;
	private PathMatcher pathMatcher = new AntPathMatcher();

	/**
	 * 提供给页面输出当前用户
	 * @return {AuthUser}
	 */
	public AuthUser currentUser() {
		return SecurityUtils.getUser();
	}

	/**
	 * 判断请求是否有权限
	 *
	 * @param request        HttpServletRequest
	 * @param authentication 认证信息
	 * @return 是否有权限
	 */
	public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
		AuthUser authUser = SecurityUtils.getUser(authentication);
		if (authUser == null) {
			return false;
		}
		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
		if (authorities.isEmpty()) {
			return false;
		}
		Integer adminId = authUser.getUserId();
		List<Resource> resourceList = resourceService.findAllByAdminId(adminId);
		for (Resource resource : resourceList) {
			String url = resource.getUrl();
			if (StringUtils.isBlank(url)) {
				continue;
			}
			if (pathMatcher.match(url, request.getRequestURI())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 判断按钮是否有xxx:xxx权限
	 * @param permission 权限
	 * @return {boolean}
	 */
	public boolean hasPermission(String permission) {
		if (StringUtils.isBlank(permission)) {
			return false;
		}
		Authentication authentication = SecurityUtils.getAuthentication();
		if (authentication == null) {
			return false;
		}
		AuthUser authUser = SecurityUtils.getUser(authentication);
		if (authUser == null) {
			return false;
		}
		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
		for (GrantedAuthority grantedAuthority : authorities) {
			String authority = grantedAuthority.getAuthority();
			if (StringUtils.isBlank(authority)) {
				continue;
			}
			if (authority.equalsIgnoreCase(permission)) {
				return true;
			}
		}
		return false;
	}
}
